<template>
  <div>
    <Category :scene="scene"></Category>
    <el-card shadow="always" style="margin-top: 10px">
      <div v-show="scene == 0">
        <el-button
          type="primary"
          size="default"
          :icon="Plus"
          style="margin-bottom: 10px"
          @click="addAttr"
          :disabled="!categoryStore.c3Id"
          >添加属性</el-button
        >
        <!--属性控件--->
        <el-tree :data="treeData"></el-tree>

        <el-table border stripe :data="attrList">
          <el-table-column label="序号" width="80" type="index" align="center">
          </el-table-column>
          <el-table-column
            label="属性名称"
            width="120"
            prop="attrName"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column label="属性值名称" align="center">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 0px 3px"
                class="ml-2"
                :type="attrVal.id % 2 == '0' ? 'success' : 'warning'"
                v-for="(attrVal, index) in row.attrValueList"
                :key="attrVal.id"
                >{{ attrVal.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="removeAttr(row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-show="scene == 1">
        <el-form ref="form" :inline="true">
          <el-form-item label="属性名">
            <el-input
              placeholder="输入属性的名字"
              size="normal"
              clearable
              v-model="attrParams.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          :icon="Plus"
          :disabled="!attrParams.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button @click="cancel">取消</el-button>
        <el-table
          border
          stripe
          style="margin: 10px 0px"
          :data="attrParams.attrValueList"
        >
          <el-table-column type="index" align="center" width="80" label="序号">
          </el-table-column>
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc) => (inputArr[$index] = vc)"
                v-if="row.flag"
                placeholder="输入属性值"
                size="small"
                v-model="row.valueName"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="save"
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
  Plus,
  UploadFilled,
} from "@element-plus/icons-vue";
import useCategoryStore from "../../../stores/category";

let categoryStore = useCategoryStore();
import { watch, ref, reactive, nextTick, onUnmounted } from "vue";
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
} from "../../../api/product/attr/attr";
import { ElMessage } from "element-plus";
//引入深拷贝
import _ from "lodash";

//引入数据类型
import type {
  attrResponseData,
  attrModel,
  attrValueModel,
} from "../../../api/product/attr/model/attr";

let attrList = ref<attrResponseData>([]);
let inputArr = ref<any>([]);

let attrParams = reactive<attrModel>({
  attrName: "",
  categoryId: "",
  categoryLevel: 3,
  attrValueList: [],
});

let scene = ref<number>(0);

let treeData = ref([]);
watch(
  () => categoryStore.c3Id,
  () => {
    if (categoryStore.c3Id == "") return;
    getAttrList();
  }
);
const getAttrList = async () => {
  let result: attrResponseData = await reqAttrList(
    categoryStore.c1Id,
    categoryStore.c2Id,
    categoryStore.c3Id
  );

  attrList.value = result;
};
//添加属性按钮的回调
const addAttr = () => {
  scene.value = 1;
  Object.assign(attrParams, {
    attrName: "",
    categoryId: categoryStore.c3Id,
    categoryLevel: 3,
    attrValueList: [],
  });
};
//取消按钮的点击事件
const cancel = () => {
  scene.value = 0;
};

const addAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag: true,
  });
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus();
  });
};

const toLook = (row: attrValueModel, $index: number) => {
  if (row.valueName.trim() == "") {
    ElMessage({
      type: "warning",
      message: "属性值不能为空",
    });
    attrParams.attrValueList.splice($index, 1);
    return;
  }
  let repeat = attrParams.attrValueList.find((item) => {
    if (row != item) {
      return row.valueName === item.valueName;
    }
  });

  if (repeat) {
    ElMessage({
      type: "warning",
      message: `${repeat.valueName}重复?`,
    });
    attrParams.attrValueList.splice($index, 1);
    return;
  }

  row.flag = false;
  console.log(inputArr.value);
};
const toEdit = (row: attrValueModel, $index: number) => {
  row.flag = true;

  nextTick(() => {
    inputArr.value[$index].focus();
  });
};
const save = async () => {
  attrParams.attrValueList.forEach((item) => {
    if (item.hasOwnProperty("flag")) {
      delete item.flag;
    }
  });
  try {
    //添加属性成功
    await reqAddOrUpdateAttr(attrParams);
    scene.value = 0;

    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "添加成功",
    });
    //获取全部最新的属性的数据
    getAttrList();
  } catch (error) {
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改失败" : "添加失败",
    });
  }
};

//修改按钮
const updateAttr = (row: attrModel) => {
  scene.value = 1;
  //深拷贝
  Object.assign(attrParams, _.cloneDeep(row));
};

const removeAttr = async (row: attrModel) => {
  try {
    await reqDeleteAttr(row.id);

    ElMessage({
      type: "success",
      message: `删除${row.attrName}成功`,
      duration: 500,
    });

    getAttrList();
  } catch (error) {
    ElMessage({
      type: "error",
      message: `删除${row.attrName}失败`,
      duration: 500,
    });
  }
};

//组件销毁钩子
onUnmounted(() => {
  //组件销毁的时候。情况仓库里面的数据
  categoryStore.c1Id = "";
  categoryStore.c2Id = "";
  categoryStore.c3Id = "";
  categoryStore.c1List = [];
  categoryStore.c2List = [];
  categoryStore.c3List = [];
});
</script>

<style scoped>
</style>